package com.gzhryc.shared_device.oem.micro.api.controllers.xcx.v1;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.IDTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.secruity.AESTools;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.PayServiceFactory;
import com.gzhryc.shared_device.oem.code.member.LoginMember;
import com.gzhryc.shared_device.oem.code.member.LoginMemberSessionManager;
import com.gzhryc.shared_device.oem.code.member.dao.db.Member;
import com.gzhryc.shared_device.oem.code.member.dao.enums.MemberEnum;
import com.gzhryc.shared_device.oem.code.member.services.MemberService;
import com.gzhryc.shared_device.oem.micro.api.MicroConstants;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.WxLoginCheckRequest;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.WxLoginCheckResponse;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.WxRegisterRequest;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.WxRegisterResponse;
import com.gzhryc.weixin.xcx.XcxAuthorityApi;
import com.gzhryc.weixin.xcx.dto.Jscode2SessionResponse;
import com.gzhryc.weixin.xcx.dto.XcxEncryptedData;

public class WXEntryController {

	static Logger log = Logger.getLogger(WXEntryController.class);

	@Route(value = { "/xcx/v1/wx/login/check.do" })
	public WxLoginCheckResponse checkLogin(HttpServletRequest request) {
		WxLoginCheckResponse apiResp = new WxLoginCheckResponse(ClientAPICodeConstants.EXECUTE_ERROR, "登陆失败，请稍后再试！");
		WxLoginCheckRequest apiReq = WebUtils.getJsonRequest(request, WxLoginCheckRequest.class);
		if (apiReq != null) {
			String appId = apiReq.getBody().getAppId();
			String code = apiReq.getBody().getCode();
			if (StringUtils.isNotBlank(appId) && StringUtils.isNotBlank(code)) {
				log.info("[/xcx/v1/wx/login/check.do]参数：code = " + code + "，appId = " + appId);
				PayServiceFactory.AppConfig config = PayServiceFactory.self().getWxConfig(appId);
				if (config != null) {
					MemberService memberService = MemberService.self();
					try {
						XcxAuthorityApi xcxApi = new XcxAuthorityApi(config.getAppId(), config.getAppSecret());
						Jscode2SessionResponse data = xcxApi.jscode2Session(code);
						if (data != null && StringUtils.isNotBlank(data.getOpenid())) {
							Member member = memberService.getByTypeAndExId(MemberEnum.Type.WxUser.index(), config.getAppId(),data.getOpenid());
							if (member == null) {
								member = new Member();
								member.setNickname(MicroConstants.MemberDefaultName);
								member.setType(MemberEnum.Type.WxUser.index());
								member.setAppId(config.getAppId());
								member.setOpenId(data.getOpenid());
								member = memberService.add(member);
								if (member == null) {
									throw new LogicException("注册微信用户失败");
								}
							}

							String loginToken = IDTools.getUUID();
							LoginMember loginMember = ClassTools.copy(new LoginMember(), member);
							loginMember.setLoginToken(loginToken);
							if (LoginMemberSessionManager.self().setMemberSession(loginMember)) {
								memberService.login(member.getId());
								String resDomain = MicroConstants.getResDomain(request);
								apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
								apiResp.getBody().setMemberId(member.getId().toString());
								apiResp.getBody().setMemberName(member.getNickname());
								apiResp.getBody().setMemberFaceImg(WebUtils.setHttpDomain(resDomain,member.getFaceImg()));
								apiResp.getBody().setLoginToken(loginToken);
								apiResp.getBody().setSessionKey(data.getSession_key());

								if (StringTools.isNotBlank(member.getPhone())) {
									apiResp.getBody().setMemberPhone(member.getPhone());
									apiResp.getBody().setLoginLevel(3);
								} else if (MicroConstants.MemberDefaultName.equals(member.getNickname())) {
									apiResp.getBody().setLoginLevel(1);
								} else {
									apiResp.getBody().setLoginLevel(2);
								}
							} else {
								log.error("缓存会员信息失败，会员信息：{{0:json}}", member);
							}
						} else {
							log.error("未找到指定的微信配置，APPID={{0}}", appId);
						}
					} catch (Exception e) {
						log.error(e.getMessage(), e);
					}
				} else {
					log.error("未找到指定的微信配置，APPID={{0}}", appId);
				}
			}
		}
		return apiResp;
	}

	@Route(value = { "/xcx/v1/wx/phone/register.do" })
	public WxRegisterResponse registerPhone(HttpServletRequest request) {
		WxRegisterResponse apiResp = new WxRegisterResponse(ClientAPICodeConstants.EXECUTE_ERROR, "注册失败，请稍后再试！");
		WxRegisterRequest apiReq = WebUtils.getJsonRequest(request, WxRegisterRequest.class);
		if (apiReq != null) {
			String encryptedData = apiReq.getBody().getEncryptedData();
			String sessionKey = apiReq.getBody().getSessionKey();
			String iv = apiReq.getBody().getIv();
			String appId = apiReq.getBody().getAppId();
			Long memberId = apiReq.getBody().getMemberId();
			if (StringUtils.isNotBlank(encryptedData) && StringUtils.isNotBlank(sessionKey) && StringUtils.isNotBlank(iv) && StringUtils.isNotBlank(appId)) {
				String json = AESTools.get().decryptBase64(encryptedData, sessionKey, iv, "UTF-8");
				if (StringUtils.isNotBlank(json)) {
					MemberService memberService = MemberService.self();
					log.info("获取微信小程序解码信息：{{0}}", json);
					XcxEncryptedData data = JsonTools.fromJson(json, XcxEncryptedData.class);
					if (data != null) {
						String phone = data.getPurePhoneNumber();
						Member member = memberService.getById(memberId);
						if (member != null) {
							if(StringTools.isNotBlank(member.getPhone())){
								apiResp.setMsg("会员已注册手机号");
								return apiResp;
							}
							if(memberService.updatePhone(member.getId(),phone)) {
								String loginToken = IDTools.getUUID();
								LoginMember loginMember = ClassTools.copy(new LoginMember(), member);
								loginMember.setLoginToken(loginToken);
								if (LoginMemberSessionManager.self().setMemberSession(loginMember)) {
									memberService.login(member.getId());
									String resDomain = MicroConstants.getResDomain(request);
									apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
									apiResp.getBody().setMemberId(member.getId().toString());
									apiResp.getBody().setMemberName(member.getNickname());
									apiResp.getBody().setMemberPhone(phone);
									apiResp.getBody().setMemberFaceImg(WebUtils.setHttpDomain(resDomain, member.getFaceImg()));
									apiResp.getBody().setLoginToken(loginToken);
								}
							}
						}
					}
				}else{
					apiResp.setMsg("微信授权失败，请删除小程序重新扫码");
					return apiResp;
				}
			}else{
				apiResp.setMsg("微信授权失败，请删除小程序重新扫码");
				return apiResp;
			}
		}
		return apiResp;
	}
}
